# views.py

import re
from datetime import datetime

from django.http import HttpResponse
from django.shortcuts import render_to_response
from django.http import HttpResponseRedirect

from titiaccount.app.account.models import Account
from titiaccount.app.account.models import Transaction
from titiaccount.app.account.models import Tag

def report(request):
    try:
        user = request.session['user']
        return render_to_response('account/report/report.html', {})
    except:
        return HttpResponseRedirect('/')

def query(request):
    #try:
    user = request.session['user']
    try:
        account_name = request.GET['account_name']
        if account_name == '':
            account_name = None
    except:
        account_name = None
    try:
        description = request.GET['description']
        if description == '':
            description = None
    except:
        description = None
    try:
        min_amount = request.GET['min_amount']
        if min_amount == '':
            min_amount = None
    except:
        min_amount = None
    try:
        max_amount = request.GET['max_amount']
        if max_amount == '':
            max_amount = None
    except:
        max_amount = None
    try:
        income = request.GET['is_income']
        if income == 'in':
            is_income = True
        elif income == 'out':
            is_income = False
        else:
            is_income = None
    except:
        is_income = None
    try:
        tag_name = request.GET['tag']
        tag = Tag.get_by_name(tag_name, user.email)
    except:
        tag = None
    try:
        min_date = request.GET['min_date']
        if min_date == '':
            min_date = None
    except:
        min_date = None
    try:
        max_date = request.GET['max_date']
        if max_date == '':
            max_date = None
    except:
        max_date = None
    try:
        favorite = request.GET['favorite']
    except:
        favorite = None

    page = 1
    page_size = 1000

    if request.is_ajax():
        return HttpResponse(Transaction.all_by_owner_json(user.email, tag, favorite, min_date, max_date, page = page, page_size = page_size, account_name = account_name, is_income = is_income, min_amount = min_amount, max_amount = max_amount), mimetype='text/plain')
    else:
        return render_to_response('account/transaction/list.html', {'transactions': Transaction.all_by_account(account)})

    return render_to_response('account/report/report.html', {})
    #except:
        #return HttpResponseRedirect('/')
